package com.wlstock.funi.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;
import com.wlstock.funi.model.SelfFundHisModel;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * Created by admin on 16/9/25.
 */

public class SelfFundHisDao {

    private static SelfFundHisDao instance;
    private DataBaseHelper  dbHelper;
    private Dao<SelfFundHisModel, Integer> hisDao;
    private Context   mContext;

    private SelfFundHisDao(Context mContext) {
        this.mContext = mContext;
        try {
            dbHelper = DataBaseHelper.getHelper(mContext);
            hisDao = dbHelper.getDao(SelfFundHisModel.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static SelfFundHisDao getInstance(Context mContex) {
        if (instance == null) {
            synchronized (SelfFundHisDao.class) {
                if (instance == null) {
                    instance = new SelfFundHisDao(mContex);
                }
            }
        }
        return instance;
    }

    /**
     * 根据最新的realDate查询这个周期数据最后的那个历史数据
     * @param stkCode  代码
     * @param periodStr 周期的String
     * @return
     */
    public SelfFundHisModel queryLastPeriodModel(String stkCode, String periodStr) {
        try {
            SelfFundHisModel model = hisDao.queryBuilder().orderBy("realDate", false).where().eq("stkCode", stkCode).and().eq("periodStr", periodStr).queryForFirst();
            return model;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 事务插入数据
     * @param models
     */
    public void createOrUpDateDatas(final List<SelfFundHisModel> models) {
        try {
            TransactionManager.callInTransaction(dbHelper.getConnectionSource(), new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    for (SelfFundHisModel model : models){
                        createOrUpdate(model);
                    }
                    return null;
                }
            });
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void createOrUpdate(SelfFundHisModel model) {
        try {
            hisDao.createOrUpdate(model);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public List<SelfFundHisModel> queryAll() {
        try {
            List<SelfFundHisModel> query = hisDao.queryBuilder().orderBy("lastUpdateDate",false).query();
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
